function wseDataFactory () {
    this.tableData = null;
    this.activeBtn = 1;
    var me = this;
    // 获取蓄水动态评价表格数据
    this.loadData = function () {
        var def = $.Deferred();
        $.getJSON("/jsite-szy-dispatch/a/szy/dispatch/ddsWeWs/listAllToMap", function (data) {
            me.tableData = data;
            def.resolve();
        });
        return def.promise();
    }
}
function getAVG(data) {
    if(data.length>0){
        var sum =data.reduce(function (p1,c) {return c+=p1})
        // var sum = data.reduce((previous, current) => current += previous);
        var avg=sum / data.length;
        return parseInt(avg);
    }else{return 0;}
}

wseDataFactory.prototype = {
    // 从tableData中获取年份数据
    getYearsFromTableData: function () {
        var data = this.tableData;
        var result = [];
        for (var year in data) {
            result.push({
                'text': year,
                'value': year
            });
        }
        return result;
    },

    getChartData: function () {
        var data = this.tableData;
        var result = {},titleYear=2017,data0_above=[],data0_under=[],data0_other=[],data1_above=[],data1_under=[],data1_other=[];
        for (var year in data) {
            titleYear=parseInt(year);
            for(var temp=0,l=data[year].length;temp<l;temp++){
                var tempdata=data[year][temp];
                if(tempdata.regType==0){
                    data0_above.push(parseFloat(tempdata.above));
                    data0_under.push(parseFloat(tempdata.under));
                    data0_other.push(parseFloat(tempdata.other));
                }else if(tempdata.regType==1){
                    data1_above.push(parseFloat(tempdata.above));
                    data1_under.push(parseFloat(tempdata.under));
                    data1_other.push(parseFloat(tempdata.other));
                }
            }
        }
        result={
            "0":{
                title: titleYear+'年行政分区地表水供水组成图',
                serieData: [{
                    type: 'pie',
                    size: '80%',
                    name: '占比',
                    data: [{y:getAVG(data0_above),
                            name:'地表水水源'},
                        {y:getAVG(data0_under),
                            name:'地下水水源'},
                        {y:getAVG(data0_other),
                            name:'其他水源'}]
                }]
            },
            "1":{
                title: titleYear+'年水资源分区地表水供水组成图',
                serieData: [{
                    type: 'pie',
                    size: '80%',
                    name: '占比',
                    data:[{y:getAVG(data1_above),
                        name:'地表水水源'},
                        {y:getAVG(data1_under),
                            name:'地下水水源'},
                        {y:getAVG(data1_other),
                            name:'其他水源'}]
                }]
            }
        }
        return result;
    },
    setTableDataByType: function () {
        var year = Ext.getCmp("wseCombo").getValue();
        var currentData = this.tableData[year];
        var type = this.activeBtn;
        var grepData = $.grep(currentData, function (obj) {
            return obj.regType == type;
        });
        Ext.data.StoreManager.lookup('wse_store1').setData(grepData);
    }
}



var wseData;
Ext.define('Admin.view.evaluation.wse.WseController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.wseController',
    views: ['Admin.view.evaluation.wse.Wse'],
    buildChart: function (dom) {
        var chartId = dom.el.id + "-body";
        _wseChart.init(chartId);
    },
    initData: function (_this, opt) {
        var myMask = new Ext.LoadMask(Ext.ComponentQuery.query('wse')[0], { msg: "正在加载..." });
        myMask.show();
        var me = this;
        wseData = new wseDataFactory();
        $.when(wseData.loadData())
            .done(function () {
                _wseChart.dataMap=wseData.getChartData();
                // 设置年份数据
                var yearData = wseData.getYearsFromTableData();
                var firstSelect = yearData.length > 0 ? yearData[0].value : '';
                var year_store = Ext.create('Ext.data.Store', {
                    fields: ['text', 'value'],
                    data: yearData
                });
                Ext.create('Ext.form.ComboBox', {
                    renderTo: 'wseComboWrapper',
                    id: 'wseCombo',
                    labelWidth: 35,
                    emptyText: '请选择',
                    fieldLabel: "年份",
                    valueField: 'value',
                    displayField: 'text',
                    value: firstSelect,
                    editable: false,
                    store: year_store,
                    listeners: {
                        'change': me.changeYear
                    }
                });
                Ext.getCmp('wseBtn1').fireEvent('click');
                myMask.hide();
            });
    },
    changeYear: function (_this, newVal, oldVal, opt) {
        wseData.setTableDataByType();
    },
    switchAdminRegion: function () {
        const type = 0;
        wseData.activeBtn = type;
        wseData.setTableDataByType();
        _wseChart.chartType = "0";
        if (_wseChart.chartid !== null) {
            _wseChart.change();
        }
    },
    switchWaterRegion: function () {
        const type = 1;
        wseData.activeBtn = type;
        wseData.setTableDataByType();
        _wseChart.chartType = "1";
        if (_wseChart.chartid !== null) {
            _wseChart.change();
        }
    },
})

function wseChart(id) {
    this.dataMap = {
        "0":{
            title: '2017年行政分区地表水供水组成图',
            serieData: [{
                type: 'pie',
                size: '80%',
                name: '占比',
                data: [{y:3,
                    name:'地表水水源'},
                    {y:6,
                        name:'地下水水源'},
                    {y:2,
                        name:'其他水源'}]
            }]
        },
        "1":{
            title: '2017年水资源分区地表水供水组成图',
            serieData: [{
                type: 'pie',
                size: '80%',
                name: '占比',
                data: [{y:4,
                    name:'地表水水源'},
                    {y:6,
                        name:'地下水水源'},
                    {y:2,
                        name:'其他水源'}]
            }]
        }
    };
    this.chartid = null;
    this.chartType = "0";
}

wseChart.prototype = {
    init: function (id) {
        var data = this.dataMap[this.chartType];
        this.chartid = id;
        $('#' + id).highcharts(this.getOption(data));
    },
    change: function () {
        var data = this.dataMap[this.chartType];
        $('#' + this.chartid).highcharts(this.getOption(data));
    },
    getOption: function (data) {
        return {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: data.title
            },
            tooltip: {
                headerFormat: '{series.name}<br>',
                pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    },
                    showInLegend: true
                }
            },
            series: data.serieData,
            credits: { enabled: false }
        };
    }
}

var _wseChart = new wseChart();

